<template>
  <div class="terrain3d-login-wrap" ref="loginWrap">
    <!-- 3D地形画布 -->
    <canvas ref="terrainCanvas" class="terrain-canvas"></canvas>

    <div class="login-container">
      <div class="login-panel">
        <div class="panel-header">
          <div class="logo-section">
            <div class="terrain-logo">
              <div class="logo-mountain">
                <div class="mountain-peak peak-1"></div>
                <div class="mountain-peak peak-2"></div>
                <div class="mountain-peak peak-3"></div>
                <div class="mountain-base"></div>
              </div>
            </div>
            <h2 class="terrain-title">ERP管理系统</h2>
            <p class="terrain-subtitle">探索商业高峰</p>
          </div>
        </div>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <div class="input-wrapper">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="large"
                prefix-icon="User"
                class="terrain-input"
              />
              <div class="input-shadow"></div>
            </div>
          </el-form-item>

          <el-form-item prop="password">
            <div class="input-wrapper">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                class="terrain-input"
                show-password
              />
              <div class="input-shadow"></div>
            </div>
          </el-form-item>

          <el-form-item>
            <div class="remember-forgot">
              <el-checkbox v-model="rememberMe" class="terrain-checkbox">
                <span>记住我</span>
              </el-checkbox>
              <a class="terrain-link" @click="forgotPassword">忘记密码？</a>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="terrain-button"
              :loading="loading"
              @click="handleLogin"
            >
              <span>开始征程</span>
            </el-button>
          </el-form-item>
        </el-form>

        <div class="panel-footer">
          <p class="footer-text">
            还没有账号？
            <a class="terrain-link" @click="register">立即注册</a>
          </p>
        </div>
      </div>
    </div>

    <!-- 环境控制 -->
    <div class="environment-controls">
      <div class="control-item">
        <span class="control-label">海拔</span>
        <input type="range" min="0" max="100" v-model="terrainConfig.height" />
      </div>
      <div class="control-item">
        <span class="control-label">细节</span>
        <input type="range" min="1" max="10" v-model="terrainConfig.detail" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const store = useUserStore()

const emit = defineEmits(['login'])

const loginWrap = ref(null)
const terrainCanvas = ref(null)
const loginFormRef = ref(null)
const loading = ref(false)
const rememberMe = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const terrainConfig = reactive({
  height: 50,
  detail: 5
})

const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    const response = await store.login(loginForm)

    if (response.code === 200) {
      ElMessage.success(response.msg || '登录成功')
      emit('login', response)
      router.push('/dashboard')
    } else {
      ElMessage.error(response.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '网络请求失败，请重试')
  } finally {
    loading.value = false
  }
}

const register = () => {
  ElMessage.info('注册功能开发中...')
}

const forgotPassword = () => {
  ElMessage.info('忘记密码功能开发中...')
}

let animationId = null
let cameraZ = 0

// 创建3D地形
const createTerrain = () => {
  const canvas = terrainCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight

  renderTerrain()
}

const renderTerrain = () => {
  const canvas = terrainCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 天空渐变
  const skyGradient = ctx.createLinearGradient(0, 0, 0, canvas.height / 2)
  skyGradient.addColorStop(0, '#87CEEB')
  skyGradient.addColorStop(0.5, '#E0F6FF')
  ctx.fillStyle = skyGradient
  ctx.fillRect(0, 0, canvas.width, canvas.height / 2)

  // 地形
  const points = Math.floor(terrainConfig.detail * 20)
  const gap = canvas.width / points
  const maxHeight = terrainConfig.height * 2
  const baseHeight = canvas.height / 2

  ctx.beginPath()
  ctx.moveTo(0, baseHeight)

  for (let i = 0; i <= points; i++) {
    const x = i * gap
    const noise = (Math.sin(i * 0.1 + cameraZ * 0.01) + 
                   Math.cos(i * 0.05 + cameraZ * 0.015) * 0.5 +
                   Math.sin(i * 0.03 + cameraZ * 0.02) * 0.3) * maxHeight
    const y = baseHeight + noise * (1 - Math.abs(i / points - 0.5) * 2)
    ctx.lineTo(x, y)
  }

  ctx.lineTo(canvas.width, canvas.height)
  ctx.lineTo(0, canvas.height)
  ctx.closePath()

  // 地形渐变
  const terrainGradient = ctx.createLinearGradient(0, baseHeight, 0, canvas.height)
  terrainGradient.addColorStop(0, '#8B7355')
  terrainGradient.addColorStop(0.3, '#9B8B6F')
  terrainGradient.addColorStop(0.7, '#7A6B55')
  terrainGradient.addColorStop(1, '#6B5B47')
  ctx.fillStyle = terrainGradient
  ctx.fill()

  // 地形轮廓
  ctx.strokeStyle = '#5A4A3A'
  ctx.lineWidth = 2
  ctx.stroke()

  // 添加细节纹理
  for (let i = 0; i < points; i++) {
    const x = i * gap
    const noise = (Math.sin(i * 0.1 + cameraZ * 0.01) + 
                   Math.cos(i * 0.05 + cameraZ * 0.015) * 0.5 +
                   Math.sin(i * 0.03 + cameraZ * 0.02) * 0.3) * maxHeight
    const y = baseHeight + noise * (1 - Math.abs(i / points - 0.5) * 2)
    
    // 随机添加石头
    if (Math.random() > 0.95) {
      ctx.fillStyle = '#4A3A2A'
      ctx.beginPath()
      ctx.arc(x, y, 5 + Math.random() * 5, 0, Math.PI * 2)
      ctx.fill()
    }
    
    // 随机添加草
    if (Math.random() > 0.98) {
      const grassHeight = 3 + Math.random() * 7
      ctx.strokeStyle = '#4A7C2E'
      ctx.lineWidth = 2
      ctx.beginPath()
      ctx.moveTo(x, y)
      ctx.lineTo(x - 2 + Math.random() * 4, y - grassHeight)
      ctx.stroke()
    }
  }

  // 云朵
  drawClouds(ctx)

  cameraZ += 0.5
  animationId = requestAnimationFrame(renderTerrain)
}

const drawClouds = (ctx) => {
  const cloudCount = 5
  
  for (let i = 0; i < cloudCount; i++) {
    const x = (i * 300 + cameraZ * 0.5) % (window.innerWidth + 200) - 100
    const y = 50 + i * 40
    
    ctx.fillStyle = 'rgba(255, 255, 255, 0.6)'
    ctx.beginPath()
    ctx.arc(x, y, 30, 0, Math.PI * 2)
    ctx.arc(x + 40, y, 40, 0, Math.PI * 2)
    ctx.arc(x + 80, y, 35, 0, Math.PI * 2)
    ctx.fill()
  }
}

const handleMouseMove = (e) => {
  const canvas = terrainCanvas.value
  if (!canvas) return

  const mouseX = e.x
  const rect = canvas.getBoundingClientRect()
  const relativeX = (mouseX / rect.width) * 200 - 100
  
  terrainConfig.detail = Math.max(1, Math.min(10, 5 + relativeX * 0.01))
}

const handleResize = () => {
  createTerrain()
}

onMounted(async () => {
  await nextTick()
  createTerrain()
  window.addEventListener('resize', handleResize)
  if (loginWrap.value) {
    loginWrap.value.addEventListener('mousemove', handleMouseMove)
  }
})

onUnmounted(() => {
  if (animationId) {
    cancelAnimationFrame(animationId)
  }
  window.removeEventListener('resize', handleResize)
  if (loginWrap.value) {
    loginWrap.value.removeEventListener('mousemove', handleMouseMove)
  }
})

watch(() => terrainConfig.height, () => {
  // 配置变化时重新渲染
})
</script>

<style scoped>
.terrain3d-login-wrap {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #87CEEB;
}

.terrain-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.login-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.login-panel {
  position: relative;
  width: 450px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.5);
  border-radius: 20px;
  padding: 50px 40px;
  box-shadow: 
    0 20px 60px rgba(0, 0, 0, 0.3),
    0 0 0 1px rgba(255, 255, 255, 0.5) inset;
}

.panel-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-section {
  position: relative;
}

.terrain-logo {
  width: 120px;
  height: 120px;
  margin: 0 auto 25px;
  position: relative;
}

.logo-mountain {
  width: 100%;
  height: 100%;
  position: relative;
}

.mountain-peak {
  position: absolute;
  bottom: 20px;
  width: 0;
  height: 0;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
}

.peak-1 {
  left: 20%;
  border-left: 25px solid transparent;
  border-right: 25px solid transparent;
  border-bottom: 50px solid #8B7355;
  animation: mountainShift 4s ease-in-out infinite;
}

.peak-2 {
  left: 50%;
  transform: translateX(-50%);
  border-left: 35px solid transparent;
  border-right: 35px solid transparent;
  border-bottom: 70px solid #7A6B55;
  z-index: 2;
  animation: mountainShift 4s ease-in-out infinite 0.5s;
}

.peak-3 {
  right: 20%;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-bottom: 40px solid #9B8B6F;
  animation: mountainShift 4s ease-in-out infinite 1s;
}

.mountain-base {
  position: absolute;
  bottom: 20px;
  left: 5%;
  width: 90%;
  height: 60px;
  background: linear-gradient(to bottom, #7A6B55, #6B5B47);
  border-radius: 10px;
  opacity: 0.8;
}

@keyframes mountainShift {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-5px); }
}

.terrain-title {
  font-size: 32px;
  font-weight: bold;
  color: #2C3E50;
  margin: 0 0 10px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.terrain-subtitle {
  font-size: 14px;
  color: #7A6B55;
  margin: 0;
  letter-spacing: 2px;
}

.login-form {
  width: 100%;
}

.input-wrapper {
  position: relative;
  margin-bottom: 30px;
}

.terrain-input {
  width: 100%;
}

:deep(.el-input__wrapper) {
  background: #f8f9fa;
  border: 2px solid #e9ecef;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  border-radius: 12px;
}

:deep(.el-input__wrapper:hover) {
  border-color: #8B7355;
  box-shadow: 0 4px 12px rgba(139, 115, 85, 0.2);
}

:deep(.el-input.is-focus .el-input__wrapper) {
  border-color: #8B7355;
  box-shadow: 0 0 0 3px rgba(139, 115, 85, 0.1);
  background: white;
}

:deep(.el-input__inner) {
  color: #2C3E50;
}

.input-shadow {
  position: absolute;
  bottom: -5px;
  left: 10%;
  width: 80%;
  height: 10px;
  background: radial-gradient(ellipse, rgba(139, 115, 85, 0.3), transparent);
  transform: scaleY(0);
  transition: transform 0.3s;
}

:deep(.el-input.is-focus ~ .input-shadow) {
  transform: scaleY(1);
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.terrain-checkbox :deep(.el-checkbox__label) {
  color: #2C3E50;
  font-size: 14px;
}

.terrain-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #8B7355;
  border-color: #8B7355;
}

.terrain-link {
  color: #8B7355;
  font-size: 14px;
  cursor: pointer;
  text-decoration: none;
  transition: all 0.3s;
  font-weight: 500;
}

.terrain-link:hover {
  color: #6B5B47;
  text-decoration: underline;
}

.terrain-button {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #8B7355, #6B5B47);
  border: none;
  color: white;
  font-size: 16px;
  font-weight: bold;
  letter-spacing: 2px;
  border-radius: 12px;
  transition: all 0.3s;
  box-shadow: 0 4px 15px rgba(139, 115, 85, 0.4);
}

.terrain-button:hover {
  background: linear-gradient(135deg, #9B8B6F, #7A6B55);
  box-shadow: 0 6px 20px rgba(139, 115, 85, 0.5);
  transform: translateY(-2px);
}

.terrain-button:active {
  transform: translateY(0);
}

:deep(.terrain-button.is-loading) {
  background: linear-gradient(135deg, #9B8B6F, #7A6B55);
}

.panel-footer {
  text-align: center;
  margin-top: 20px;
}

.footer-text {
  color: #7A6B55;
  font-size: 14px;
}

/* 环境控制 */
.environment-controls {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 15px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  z-index: 100;
  min-width: 200px;
}

.control-item {
  margin-bottom: 15px;
}

.control-item:last-child {
  margin-bottom: 0;
}

.control-label {
  display: block;
  color: #2C3E50;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 8px;
}

.control-item input[type="range"] {
  width: 100%;
  appearance: none;
  height: 6px;
  background: #e9ecef;
  border-radius: 3px;
  outline: none;
}

.control-item input[type="range"]::-webkit-slider-thumb {
  appearance: none;
  width: 18px;
  height: 18px;
  background: #8B7355;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

.control-item input[type="range"]::-moz-range-thumb {
  width: 18px;
  height: 18px;
  background: #8B7355;
  border-radius: 50%;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}
</style>

